package com.songVersion.youtube;

import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import com.google.gdata.client.youtube.YouTubeQuery;
import com.google.gdata.client.youtube.YouTubeService;
import com.google.gdata.client.youtube.YouTubeQuery.OrderBy;
import com.google.gdata.client.youtube.YouTubeQuery.SafeSearch;
import com.google.gdata.data.media.mediarss.MediaPlayer;
import com.google.gdata.data.media.mediarss.MediaThumbnail;
import com.google.gdata.data.youtube.VideoEntry;
import com.google.gdata.data.youtube.VideoFeed;
import com.google.gdata.data.youtube.YouTubeMediaGroup;
import com.songVersion.model.Thumbnail;
import com.songVersion.model.YoutubeInfo;
import com.songVersion.services.YoutubeInfoManager;
import com.songVersion.services.impl.YoutubeInfoManagerImpl;

public class YoutubeSearch
{
	public static String DEVELOPER_KEY = "AI39si4t4iHIpsbGp9k-sIFCbLTsdeTnKk-Nb0grHBP7ooMifT_mJnJ4uF2K1yggDpsncOGtMjDyTZf6TLd0--6VqqzBvG714A";
	YouTubeService service;

	public YoutubeSearch()
	{
		service = new YouTubeService(DEVELOPER_KEY);
	}

	public YoutubeInfo searchVideo(String song, String author)
	{
		return doSearchOriginal(song, author);
	}
	public YoutubeInfo searchVideo(String videoId, String song, String author)
	{
		YoutubeInfo video;
		if (videoId != null && !"".equals(videoId))
		{
			YoutubeInfoManager yim = new YoutubeInfoManagerImpl();
			video = yim.fromCache(yim.loadByVideoId(videoId));
		} else
		{
			video = doSearchOriginal(song, author);
		}
		return video;
	}

	private YoutubeInfo doSearchOriginal(String song, String author)
	{
		try
		{
			YoutubeInfo res = null;
			YouTubeQuery query = new YouTubeQuery(new URL(
					"http://gdata.youtube.com/feeds/api/videos"));
			StringBuffer sb = new StringBuffer(song);
			if (author != null) sb.append(" ").append(author);
			query.setFullTextQuery(sb.toString());
			query.setOrderBy(OrderBy.RELEVANCE);
			query.setSafeSearch(SafeSearch.NONE);
			query.setStartIndex(1);
			query.setMaxResults(1);
			/*
			 * if (author != null && !author.trim().equals("")) {
			 * System.out.println("b" + author); Query.CategoryFilter
			 * categoryFilter1 = new Query.CategoryFilter();
			 * categoryFilter1.addCategory(new Category(
			 * YouTubeNamespace.KEYWORD_SCHEME, author));
			 * query.addCategoryFilter(categoryFilter1); }
			 */
			VideoFeed vf = service.query(query, VideoFeed.class);
			if (vf != null && vf.getEntries().size() > 0)
			{
				res = infoFromEntry(vf.getEntries().get(0));
				res.setPattern(song + "." + author);
			}
			return res;

		} catch (Exception e)
		{
			e.printStackTrace();
			throw new RuntimeException(e);
		}
	}

	private YoutubeInfo infoFromEntry(VideoEntry ve)
	{
		YoutubeInfo info = new YoutubeInfo();
		YouTubeMediaGroup mediaGroup = ve.getMediaGroup();
		MediaPlayer mediaPlayer = mediaGroup.getPlayer();

		info = new YoutubeInfo();
		info.setPattern(ve.getTitle().getPlainText());
		info.setPlayerUrl(mediaPlayer.getUrl());
		info.setVideoId(mediaGroup.getVideoId());

		List<Thumbnail> thumbs = new ArrayList<Thumbnail>();
		for (MediaThumbnail mt : mediaGroup.getThumbnails())
		{
			Thumbnail t = new Thumbnail();
			t.setHeight(mt.getHeight());
			t.setUrl(mt.getUrl());
			t.setWidth(mt.getWidth());
			thumbs.add(t);
			// solo cargamos el primero
			break;
		}
		info.setThumbnails(thumbs);
		return info;
	}

	public List<YoutubeInfo> doSearchCover(String song, int maxResults)
	{
		return doSearchAdded(song, "cover", maxResults);
	}

	public List<YoutubeInfo> doSearchParody(String song, int maxResults)
	{
		return doSearchAdded(song, "parody", maxResults);
	}

	public List<YoutubeInfo> doSearchAdded(String song, String added,
			int maxResults)
	{
		try
		{
			List<YoutubeInfo> res = new ArrayList<YoutubeInfo>();
			YouTubeQuery query = new YouTubeQuery(new URL(
					"http://gdata.youtube.com/feeds/api/videos"));
			query.setFullTextQuery(song + " " + added);
			query.setOrderBy(OrderBy.RELEVANCE);
			query.setSafeSearch(SafeSearch.NONE);
			query.setStartIndex(1);
			query.setMaxResults(maxResults);

			VideoFeed vf = service.query(query, VideoFeed.class);
			if (vf != null && vf.getEntries().size() > 0)
			{
				for (VideoEntry ve : vf.getEntries())
				{
					res.add(infoFromEntry(ve));
				}
			}
			return res;

		} catch (Exception e)
		{
			e.printStackTrace();
			throw new RuntimeException(e);
		}

	}

	public static void main(String[] args)
	{
		// YoutubeSearch ys = new YoutubeSearch();
		// VideoFeed vf = ys.doSearchOriginal("Princesa", "sabina");
		// YoutubeHelper.printVideoFeed(vf, true);
	}

}
